<template>
  <THeader title="调停申请">
    <template v-slot:icon>
    </template>
  </THeader>

  <van-form @submit="onSubmit">
    <!--    开始日期-->
    <van-cell-group>
      <van-cell style="font-size: 4vw; font-weight: 500">
        <span style="border: 2px solid #2b95ef;"></span>
        <span style="margin-left: 10px">申请信息</span>
      </van-cell>
      <van-field
          v-model="start"
          is-link
          required
          readonly
          name="startTime"
          label="开始日期"
          placeholdrounder="选择开始日期"
          @click="showStartPicker = true"
      />

      <van-popup v-model:show="showStartPicker" position="bottom">
        <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="开始时间"
            :formatter="formatter"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onStartConfirm"
            @cancel="showStartPicker=false"
        />
      </van-popup>
      <!--    结束日期-->
      <van-field
          v-model="end"
          is-link
          required
          readonly
          name="endTime"
          label="结束日期"
          placeholder="选择结束日期"
          @click="showEndPicker = true"
      />
      <van-popup round v-model:show="showEndPicker" position="bottom">
        <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="结束时间"
            :formatter="formatter"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onEndConfirm"
            @cancel="showEndPicker=false"
        />
      </van-popup>
      <van-field required name="type" label="类型">
        <template #label>
          类型
          <van-icon
              name="info-o"
              class="info-icon"
              @click="showInfo"
          />
        </template>
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio name="0">调课</van-radio>
            <van-radio name="1">停课</van-radio>
          </van-radio-group>
        </template>

      </van-field>

      <!--教师所属学院-->
      <van-field
          v-model="academy"
          is-link
          required
          readonly
          label="所属学院"
          name="academy"
          placeholder="选择所属学院"
          @click="showAcademy = true"
      />
      <van-popup v-model:show="showAcademy" round position="bottom">
        <van-picker
            title="所属学院"
            v-model="currentAcademy"
            :columns="academys"
            :default-index="index"
            @cancel="showAcademy = false"
            @confirm="onAcademyConfirm"
        />
      </van-popup>
      <!--理由-->

      <van-field
          v-model="message"
          rows="5"
          label="申请理由"
          name="reason"
          type="textarea"
          maxlength="100"
          placeholder="请输入"
          show-word-limit
          required
      />

    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="info" native-type="submit" color="#2b95ef">
        下一步
      </van-button>
    </div>
  </van-form>
  <v-dialog v-model:show="isShow" title="提示信息" @close="colseDialog()" style="color: #6d6d6d" confirmButtonColor="#2b95ef">
    <van-cell>
      <span style="color: #6d6d6d">【停课】</span>
      <span style="color: #6d6d6d;font-size: 3.5vw">变更上课时间,指定补课的时间及地点</span>
    </van-cell>

    <van-cell>
      <span style="color: #6d6d6d">【调课】</span>
      <span style="color: #6d6d6d;font-size: 3.5vw"> 上课时间不变，由别的老师代课</span>
    </van-cell>
    <van-cell>
      <van-icon name="info-o" color="#1989fa"/>
      <span style="font-size: 3.5vw;color: #6d6d6d;margin-left: 1vw">调停课申请由所属学院主管教学的副院长审核 非全校公选课调停课信息由任课教师通知学生</span>
    </van-cell>
    <van-cell>
      <van-icon name="info-o" color="#1989fa"/>
      <span style="font-size: 3.5vw;color: #6d6d6d;color: #6d6d6d;margin-left: 1vw">全校公选课调停课信息由任课教师通知所在学院教学科相关教学科通知其它二级学院</span>
    </van-cell>
  </v-dialog>
</template>
<script>
import {Dialog} from "vant";
import 'vant/es/dialog/style';
import {onBeforeRouteLeave, useRouter} from 'vue-router';
import {getAllCollege} from "/@/api/ttsq";
import {Toast} from 'vant';
import 'vant/es/toast/style';
import {useSelectedStore} from "/@/store/modules/fillInfo";
import {useDialogStateStore} from "/@/store/modules/dialogState";
import 'vant/es/dialog/style';
import {getCourse} from "/@/api/ttsq";

export default {
  components: {
    'v-dialog': Dialog.Component,
  },
  setup() {
    const index = ref(null)
    const isShow = ref();
    const router = useRouter();
    const obj = JSON.parse(localStorage.getItem('USERINFO'))
    let tempDate1 = null;
    let tempDate2 = null;

    const timePicker = reactive({
      start: null,
      end: null,
      currentDate: new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()),
      minDate: new Date(new Date().getFullYear() - 2, 0, 1),
      maxDate: new Date(new Date().getFullYear() + 2, 12, 1),
      showStartPicker: false,
      showEndPicker: false,
    })
    const typePicker = reactive({
      type: "1",
      types: ['停课', '调课'],//0 1
    })
    const academyPicker = reactive({
      academy: null,
      academys: [],
      currentAcademy: obj.teacher.collegeName,
      showAcademy: false,
      academyInfo: []
    })

    const getAcademy = (academy) => {
      for (let academyInfoKey in academyPicker.academyInfo) {
        if (academyPicker.academyInfo[academyInfoKey].name === academy) {
          return academyPicker.academyInfo[academyInfoKey].number
        }
      }
    }
    const getMessage = reactive({
      message: null
    })
    // 开始时间

    const initDate = () => {
      let value = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())
      const year = value.getFullYear();
      const month = value.getMonth() + 1;
      const day = value.getDate();
      timePicker.start = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      timePicker.end = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      tempDate1 = new Date(timePicker.start);
      tempDate2 = new Date(timePicker.end);

      console.log("start", timePicker.start)
    }
    const initCollege = () => {
      academyPicker.academy = obj.teacher.collegeName
      // academyPicker.currentAcademy=obj.teacher.collegeName
    }


    const onStartConfirm = (value) => {
      const year = value.getFullYear();
      const month = value.getMonth() + 1;
      const day = value.getDate();
      //选择的时间
      timePicker.start = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      //当前时间
      tempDate1 = new Date(timePicker.start);
      if (tempDate2.getTime()) {
        // 比较两个日期对象
        if ((tempDate1.getTime() > tempDate2.getTime())) {
          Toast('请正确填写日期');
          console.log("开始时间大于结束时间")
        } else if (tempDate1.getTime() <= tempDate2.getTime()) {
          console.log("开始时间小于结束时间")
        }
      }
      timePicker.showStartPicker = false;
    };
    // 结束时间
    const onEndConfirm = (value) => {
      // timePicker.end = value;

      const year = value.getFullYear();
      const month = value.getMonth() + 1;
      const day = value.getDate();

      timePicker.end = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      tempDate2 = new Date(timePicker.end);
      // 比较两个日期对象
      if (tempDate1.getTime()) {
        if (tempDate1.getTime() > tempDate2.getTime()) {
          Toast('请正确填写日期');
          // console.log("no");
        } else if (tempDate1.getTime() <= tempDate2.getTime()) {
          // console.log("yes");
        }
      }

      timePicker.showEndPicker = false;
    };

    // 学院
    const onAcademyConfirm = (value) => {
      // console.log(value)
      academyPicker.academy = value;
      academyPicker.showAcademy = false;
    };
    const dialogState = useDialogStateStore()
    // 注意事项
    const dialog = () => {
      // 弹出框 首次提示
      console.log("dialogState", dialogState.dialogState)
      if (dialogState.dialogState === true) {
        isShow.value = dialogState.dialogState
      }
    }
    const colseDialog = () => {
      dialogState.setDialogState(false)
    }
    const formatter = (type, val) => {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      return val;
    };
    const onSubmit = async (value) => {
      if (timePicker.start && timePicker.end && academyPicker.academy && typePicker.type && getMessage.message) {
        const now = new Date()
        // 忽略时、分、秒和毫秒，只比较年、月、日
        now.setHours(0, 0, 0, 0);
        tempDate1.setHours(0, 0, 0, 0);
        tempDate2.setHours(0, 0, 0, 0);
        console.log("now", now.getTime())
        console.log("tempDate1", tempDate1.getTime())
        console.log("tempDate2", tempDate2.getTime())
        if ((tempDate1.getTime() > tempDate2.getTime())) {
          Toast("请正确填写日期")
        } else {
          // if ((tempDate1.getTime() >= now.getTime()) && (tempDate2.getTime() >= now.getTime())) {
          if (getMessage.message.length < 4) Toast("申请理由不少于4个字")
          else {
            const res = await getCourse(value.startTime, value.endTime, Number(value.type));
            const resTemp = res.response.value.extend
            console.log("response888888888888888888888888888", resTemp.msg)
            if (resTemp.msg) {
              Toast(resTemp.msg)
            } else {
              await router.push({
                path: '/stop',
                query: {
                  start: value.startTime,
                  end: value.endTime,
                  type: value.type,
                  academy: getAcademy(value.academy),
                  reason: value.reason
                }
              })
            }

          }

          // } else Toast("请正确填写日期范围")


        }

      } else {
        await Dialog.alert({
          theme: 'round-button',
          confirmButtonColor: '#1989fa',
          confirmButtonText: "我知道了",
          message: "请完善申请信息 !"
        })
      }
    }

    const showInfo = () => {
      isShow.value=!isShow.value
    }
    const initData = async () => {
      const res = await getAllCollege();
      academyPicker.academyInfo = res.response.value.extend.colleges
      const obj = JSON.parse(localStorage.getItem('USERINFO'))
      for (let academyInfoKey in academyPicker.academyInfo) {
        academyPicker.academys.push(academyPicker.academyInfo[academyInfoKey].name)
        if (academyPicker.academyInfo[academyInfoKey].name === obj.teacher.collegeName) {
          index.value = academyInfoKey
        }
      }
    }

    onMounted(() => {
      dialog();
      initDate();
      formatter();
      initData();
      initCollege();
    })


    return {
      ...toRefs(timePicker),
      ...toRefs(typePicker),
      ...toRefs(academyPicker),
      ...toRefs(getMessage),
      onStartConfirm,
      onEndConfirm,
      formatter,
      onAcademyConfirm,
      onSubmit,
      isShow,
      colseDialog,
      index,
      showInfo,
    }

  }
}
</script>

<style scoped>
>>> .van-cell {
  font-size: 4vw;
  padding: 3.5vw;
}

>>> .van-dialog__message {
  text-align: left;
  line-height: 5vw;
}

.notice-swipe {
  height: 40px;
  line-height: 40px;
}
.info-icon{
  color: #1989fa;
}
</style>
